package top.zhouze.common.base;

import android.util.Log;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.jetbrains.annotations.NotNull;

/**
 * @author 周仄
 * @since 2023/2/7 14:29
 */
public abstract class RecyclerViewScrollListener extends RecyclerView.OnScrollListener {

    private boolean isSlidingUpward = false;

    /**
     * 下拉刷新
     */
    public abstract void refresh();

    /**
     * 上拉加载
     */
    public abstract void loading();

    @Override
    public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
        // 当不滑动时
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            //获取最后一个完全显示的itemPosition
            int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
            int firstItemPosition = manager.findFirstCompletelyVisibleItemPosition();
            int itemCount = manager.getItemCount();
            Log.d("tag1", "total:"+itemCount+"/first:"+firstItemPosition+"/last:"+lastItemPosition);

            if (firstItemPosition == 0 && !isSlidingUpward) {
                //刷新数据
                refresh();
            }

            // 判断是否滑动到了最后一个item，并且是向上滑动
            if (lastItemPosition == (itemCount - 1) && isSlidingUpward) {
                //加载更多
                loading();
            }
        }
    }

    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        //dy大于0上拉，dy小于0下拉
        super.onScrolled(recyclerView, dx, dy);
        isSlidingUpward = dy > 0;
    }
}
